﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Filters;
using System.Web.Mvc;

namespace AspNetDemo.Services
{
    public class MyExceptionFilter : System.Web.Http.Filters.IExceptionFilter, System.Web.Mvc.IExceptionFilter
    {
        public bool AllowMultiple { get { return false; } }

        public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            //api 
            actionExecutedContext.Response = new HttpResponseMessage()
            {
                Content = new StringContent(actionExecutedContext.Exception.Message, Encoding.UTF8),
                StatusCode = System.Net.HttpStatusCode.InternalServerError
            };
            
            return Task.FromResult(0);
        }

        public void OnException(ExceptionContext filterContext)
        {
            //mvc 
            filterContext.Result = new ContentResult() { Content = filterContext.Exception.Message };
            filterContext.ExceptionHandled = true;
        }
    }
}